package com.icoolkj.ms.user.service.impl;

import com.icoolkj.ms.api.auth.dto.AccountRegisterDTO;
import com.icoolkj.ms.common.core.enums.UserTypeEnum;
import com.icoolkj.ms.common.core.enums.AccountStatusEnum;
import com.icoolkj.ms.common.core.enums.AdminFlagEnum;
import com.icoolkj.ms.api.auth.feign.AccountRegisterFeignClient;
import com.icoolkj.ms.api.user.vo.UserApiVO;
import com.icoolkj.ms.common.core.exception.IcoolkjMSException;
import com.icoolkj.ms.common.core.response.ServerResponseEntity;
import com.icoolkj.ms.common.core.utils.BeanUtil;
import com.icoolkj.ms.common.core.utils.IpUtil;
import com.icoolkj.ms.common.core.utils.uuid.IdWorker;
import com.icoolkj.ms.user.dto.UserRegisterDTO;
import com.icoolkj.ms.user.mapper.UserMapper;
import com.icoolkj.ms.user.model.User;
import com.icoolkj.ms.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/02/19 10:56
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AccountRegisterFeignClient accountRegisterFeignClient;

    @Override
    public Long saveUserRegister(UserRegisterDTO userRegisterDTO){
        Long userId = IdWorker.nextId();
        userRegisterDTO.setUserId(userId);

        AccountRegisterDTO accountRegisterDTO = BeanUtil.map(userRegisterDTO, AccountRegisterDTO.class);
        accountRegisterDTO.setUserType(UserTypeEnum.NORMAL_USER.getCode());
        accountRegisterDTO.setStatus(AccountStatusEnum.ENABLE.getCode());
        accountRegisterDTO.setIsAdmin(AdminFlagEnum.NORMAL.getCode());
        accountRegisterDTO.setCreateIp(IpUtil.getCurrentRequestIp());

        // 保存统一账户信息
        ServerResponseEntity<Long> serverResponse = accountRegisterFeignClient.saveUserRegister(accountRegisterDTO);
        // 抛异常回滚
        if (!serverResponse.isSuccess()) {
            throw new IcoolkjMSException(serverResponse.getMessage());
        }

        User user = new User();
        user.setUserId(userId);
        user.setPic(userRegisterDTO.getPic());
        user.setNickName(userRegisterDTO.getNickName());
        user.setStatus(1);
        userMapper.saveUser(user);

        return serverResponse.getData();
    }

    public UserApiVO getUserInfoByUserId(Long userId) {
        return userMapper.getUserInfoByUserId(userId);
    }

}
